package demo4.mapper;

import demo4.pojo.user;
import demo4.util.idbutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Component
public class usermapper implements iusermapper
{
    @Autowired
    private idbutil dbutil;
    public int insert() throws SQLException {
        System.out.println("正在插入数据");
        dbutil.getConnection();
        return 0;
    }

    @Override
    public int insert(user user) {
        try(Connection con=dbutil.getConnection())
        {
           String sql="INSERT INTO USER(USERNAME,PASSWORD,NICKNAME,AGE) VALUES(?,?,?,?)";
           PreparedStatement ps=con.prepareStatement(sql);
           ps.setString(1, user.getUsername());
           ps.setString(2, user.getPassword());
           ps.setString(3, user.getNickname());
           ps.setInt(4, user.getAge());
           return ps.executeUpdate();
        } catch (SQLException e) {
          e.printStackTrace();
        }
        return 0;
    }
    public user select(String name)
    {
        try(Connection con=dbutil.getConnection())
        {
            List<user> list=new ArrayList<>();
            String sql="SELECT ID,USERNAME,PASSWORD FROM USER WHERE USERNAME=?";
            Statement ps=con.createStatement();
            ResultSet rs=ps.executeQuery(sql);
            if(rs.next())
            {
                user user=new user();
                user.setId(rs.getInt("ID"));
                user.setUsername(rs.getString("USERNAME"));
                user.setPassword(rs.getString("PASSWORD"));
                user.setNickname(rs.getString("NICKNAME"));
                user.setAge(rs.getInt("AGE"));
                list.add(user);
                return user;
            }
            return null;
        } catch (SQLException e){e.printStackTrace();}
        return null;
    }
    public List<user> select()
    {
        try(Connection con=dbutil.getConnection())
        {
            String sql="SELECT ID,USERNAME,PASSWORD,NICKNAME,AGE FROM USER";
            PreparedStatement ps=con.prepareStatement(sql);
            ResultSet rs=ps.executeQuery();
        } catch (SQLException e){e.printStackTrace();}
      return null;
    }
}
